#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using Gizmox.WebGUI.Common.Resources;

#endregion

namespace TVC.Modules.CustomControl
{
    public partial class MyDataGirdView : UserControl
    {


        DataGridView dgv = new DataGridView();
        DataGridViewCheckBoxColumn typecol = new DataGridViewCheckBoxColumn();
        //int dgvheight = 0;
        //DataTable _dtClass;
        public MyDataGirdView()
        {
            InitializeComponent();
        }

        public delegate void GridValueChanged(object sender, DataGridViewCellEventHandler e);

        public class DataGridViewCellEventHandler : System.EventArgs
        {
            private String strIA;
            private String strCA;
            private String strIB;
            private String strCB;
            private double intVal;
            private bool IsEna;

            public DataGridViewCellEventHandler(String ItemA, String ClassA, String ItemB, String ClassB, double Value, bool IsEnabled)
            {
                this.strIA = ItemA;
                this.strCA = ClassA;
                this.strIB = ItemB;
                this.strCB = ClassB;
                this.intVal = Value;
                this.IsEna = IsEnabled;
            }

            public String strItemA
            {
                get
                {
                    return strIA;
                }
            }

            public String strClassA
            {
                get
                {
                    return strCA;
                }
            }
            public String strItemB
            {
                get
                {
                    return strIB;
                }
            }

            public String strClassB
            {
                get
                {
                    return strCB;
                }
            }

            public double intValue
            {
                get
                {
                    return intVal;
                }
            }
            public bool IsEnabled
            {
                get
                {
                    return IsEna;
                }
            }

        }

        public event GridValueChanged dgv_ValueChanged;

        public delegate void GridLookupChanged(object sender, DataGridViewCellEventHandler e);
                
        public void SetHeaderText(string header, int intleft, int inttop, int intheight)
        {
            lblQuestion.Text = header;
            lblQuestion.Padding = new Gizmox.WebGUI.Forms.Padding(intleft, 0, 0, 0);
            plnTop.Padding = new Gizmox.WebGUI.Forms.Padding(0, 20, 0, 0);
            ResizeHeader(header, intheight);
        }
        
        private void ResizeHeader(string header, int intheight)
        {
            if (header != "")
            {
                Graphics g;
                Bitmap TextBitmap = new Bitmap(1, 1);
                g = Graphics.FromImage(TextBitmap);
                float width = g.MeasureString(header, lblQuestion.Font).Width;
                int ln = Convert.ToInt32(width / this.Width);
                float height = g.MeasureString(header, lblQuestion.Font).Height * (ln + 1) + 2;
                //plnTop.Height = Convert.ToInt32(height);
                plnTop.Height = plnTop.Height + 20;
                this.Height = plnTop.Height  + intheight + 100;
            }
        }

        public string GetItemID()
        {
            if (dgv.DataSource != null)
            {
                return dgv.Name;
            }
            else
                return "";
        }
        public DataTable GetdtClass()
        {
            if (dgv.DataSource != null)
            {
                DataTable dtdgv = new DataTable();
                DataTable dt = new DataTable();
                dtdgv = dgv.DataSource as DataTable;
                dt = dtdgv.Clone();
                dt.Columns.Add("colCheck");
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr["QstItemID"] = dgv.Rows[i].Cells["colQstItemID"].Value;
                    dr["ClassID"] = dgv.Rows[i].Cells["colClassID"].Value;
                    //if (_typekey == false)
                        dr["Value"] = dgv.Rows[i].Cells["colCheck"].Value;
                    //else
                    //{
                    //    if (dgv.Rows[i].Cells["colCheck"].Value == true)
                    //        dr["Value"] = 1.0;
                    //    else
                    //        dr["Value"] = 0.0;
                    //}
                        dt.Rows.Add(dr);
                }
                return dt;
            }
            else
                return null;
        }

        public void SetGridView(DataTable dt,String title,string ID, MainForm main, Dictionary<String , String> dic )
        {
            
            Gizmox.WebGUI.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new Gizmox.WebGUI.Forms.DataGridViewCellStyle();
            this.colDescription.AutoSizeMode = Gizmox.WebGUI.Forms.DataGridViewAutoSizeColumnMode.Fill;
            this.colDescription.DataPropertyName = "Description";
            dataGridViewCellStyle1.FormatProvider = new System.Globalization.CultureInfo("en-US");
            dataGridViewCellStyle1.WrapMode = Gizmox.WebGUI.Forms.DataGridViewTriState.True;
            this.colDescription.DefaultCellStyle = dataGridViewCellStyle1;
            this.colDescription.HeaderText = title;
            this.colDescription.ReadOnly = true;
            this.colDescription.Name = "colDescription";
            //this.colQstItemID.AutoSizeMode = Gizmox.WebGUI.Forms.DataGridViewAutoSizeColumnMode.Fill;
            this.colQstItemID.DataPropertyName = "QstItemID";
            this.colQstItemID.Visible = false;
            this.colQstItemID.Name = "colQstItemID";
            //this.colClassID.AutoSizeMode = Gizmox.WebGUI.Forms.DataGridViewAutoSizeColumnMode.Fill;
            this.colClassID.DataPropertyName = "ClassID";
            this.colClassID.Visible = false;
            this.colClassID.Name = "colClassID";
            this.colAnwerFrom.DataPropertyName = "AnwerFrom";
            this.colAnwerFrom.Visible = false;
            this.colAnwerFrom.Name = "colAnwerFrom";
            this.colAnwerTo.DataPropertyName = "AnwerTo";
            this.colAnwerTo.Visible = false;
            this.colAnwerTo.Name = "colAnwerTo";
            this.colClassID.DataPropertyName = "ClassID";
            this.colClassID.Visible = false;
            this.colClassID.Name = "colClassID";
            this.colLookup.DataPropertyName = "Lookup";
            this.colLookup.Visible = false;
            this.colLookup.Name = "colLookup";
            this.colLookup.Width = 100;
            this.dgv.ColumnHeadersVisible = false;
            this.dgv.RowHeadersVisible = false;
            this.dgv.BackgroundColor = System.Drawing.SystemColors.Window;
            this.dgv.BorderStyle = Gizmox.WebGUI.Forms.BorderStyle.FixedSingle;
            this.dgv.ColumnHeadersHeightSizeMode = Gizmox.WebGUI.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dgv.Columns.AddRange(new Gizmox.WebGUI.Forms.DataGridViewColumn[] {
                this.colDescription,
                this.colQstItemID,
                this.colClassID,
                this.colAnwerFrom,
                this.colAnwerTo,
                this.colLookup});
            this.dgv.AllowUserToAddRows = false;
            this.dgv.AllowUserToDeleteRows = false;
            this.dgv.BorderStyle = Gizmox.WebGUI.Forms.BorderStyle.FixedSingle;
            this.dgv.ColumnHeadersHeightSizeMode = Gizmox.WebGUI.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            //this.dgv.Location = new System.Drawing.Point(46, 56);
            this.dgv.AutoSizeRowsMode = Gizmox.WebGUI.Forms.DataGridViewAutoSizeRowsMode.AllCells;
            this.dgv.MultiSelect = false;
            this.dgv.RowTemplate.DefaultCellStyle.FormatProvider = new System.Globalization.CultureInfo("en-US");
            this.dgv.SelectionMode = Gizmox.WebGUI.Forms.DataGridViewSelectionMode.FullRowSelect;
            this.dgv.Size = new Size(System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.X, System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Y);
            this.dgv.CellFormatting += new Gizmox.WebGUI.Forms.DataGridViewCellFormattingEventHandler(this.dgv_CellFormatting);
            this.dgv.TabIndex = 3;
            dgv.CellValidated += new Gizmox.WebGUI.Forms.DataGridViewCellEventHandler(dgv_CellValidated);
            this.dgv.CellValueChanged += new Gizmox.WebGUI.Forms.DataGridViewCellEventHandler(this.dgv_CellValueChanged);
            this.dgv.ScrollBars = Gizmox.WebGUI.Forms.ScrollBars.Vertical;
            dgv.Dock = Gizmox.WebGUI.Forms.DockStyle.Fill;
            dgv.AutoGenerateColumns = false;
            dgv.Name = ID;
            
            if (_typekey)
            {
                typecol.Name = "colCheck";
                typecol.HeaderText = "Results";
                typecol.DataPropertyName = "value";
                typecol.Width = 100;
                dgv.Columns.Add(typecol);
                DataTable DataTable2 = dt;
                //for (int i = 0; i < dt.Rows.Count; i++)
                //{
                //    DataTable2.Rows[i].BeginEdit();
                    //if(Convert.ToDouble(DataTable2.Rows[i]["value"])==1.0)
                    //    DataTable2.Rows[i]["Value"] = "true";
                    //else
                //        DataTable2.Rows[i]["Value"] = "false";
                //    DataTable2.Rows[i].EndEdit();
                //    DataTable2.AcceptChanges();
                //}                
            }
            else
            {
                DataGridViewTextBoxColumn colCheck = new DataGridViewTextBoxColumn();
                //colCheck.AutoSizeMode = Gizmox.WebGUI.Forms.DataGridViewAutoSizeColumnMode.Fill;
                colCheck.DataPropertyName = "Value";
                dataGridViewCellStyle1.FormatProvider = new System.Globalization.CultureInfo("en-US");
                dataGridViewCellStyle1.WrapMode = Gizmox.WebGUI.Forms.DataGridViewTriState.True;
                colCheck.DefaultCellStyle = dataGridViewCellStyle1;
                colCheck.HeaderText = "...";
                colCheck.Name = "colCheck";
                colCheck.Width = 150;
                //txt.Name = "Check";
                dgv.Columns.Add(colCheck);                
            }

            string Code = "";
            string sErr = "";
            string filter = "Lookup <> ''";
            DataRow[] result = dt.Select(filter);
            
            foreach (DataRow row in result)
            {
                DataTable dtLook = new DataTable();
                dtLook = main.GetDataSource(row["Lookup"].ToString(), ref Code, dic, ref sErr);
                if (dtLook.Rows.Count > 0)
                {
                    for (int i = 0 ; i <dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["QstItemID"].ToString() == row["QstItemID"].ToString() && dt.Rows[i]["ClassID"].ToString() == row["ClassID"].ToString())
                            dt.Rows[i]["Value"] = dtLook.Rows[0][0].ToString();
                    }
                }
            }

            dgv.DataSource = dt;            
            this.Controls.Add(dgv);
            int heightdgv = 0;
            foreach (DataGridViewRow row in dgv.Rows)
            {
                if (!row.IsNewRow && row.Cells[0] != null)
                {
                    DataGridViewTextBoxCell ic = (DataGridViewTextBoxCell)row.Cells[0];
                    if (ic.Value.ToString().Length > 160)
                        heightdgv = 15;
                }
            }

            //dgvheight = heightdgv;      
            //heightdgv = dgv.Rows.GetRowsHeight(DataGridViewElementStates.Selected);
            //dgvheight = dt.Rows.Count * 25;
            //this.Height = plnTop.Height + heightdgv;
            int rowsHeight = dgv.Rows.GetRowsHeight(DataGridViewElementStates.Visible);
            int rowCount = dgv.Rows.GetRowCount(DataGridViewElementStates.Visible);
            int rowHeight = dgv.RowTemplate.Height;
            //int rowsToShow = Math.Min((int)MaxRowsToShow, rowCount);dgv.ColumnHeadersHeight +
            Height = rowCount * rowHeight +  plnTop.Height + heightdgv;
        }



        public bool _typekey { get; set; }
        public string language { get; set; }
        public string sErr { get; set; }
        public DataTable _dtQSI { get; set; }
        public DataTable _dtRelation { get; set; }
        public bool _Checkradio { get; set; }
        

        private void dgv_CellValidated(object sender, DataGridViewCellEventArgs e)
        {            
            if (dgv.Columns[e.ColumnIndex].Name == "colCheck")
            {                               
                //if (_typekey == false && dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
                //{
                //    string filter = "QstItemID ='" + dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value + "'";
                //    DataTable dt = new DataTable();
                //    _dtQSI.DefaultView.Table.Select(filter);
                //    if (_dtQSI.Rows.Count == 1)
                //    {
                //        double AnFrom = _dtQSI.Rows[0].Field<int>("AnswerFrom");
                //        double AnTo = _dtQSI.Rows[0].Field<int>("AnswerTo");

                //        if (AnFrom > Convert.ToDouble(dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()) &&
                //                Convert.ToDouble(dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()) > AnTo)
                //        {
                //            dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = AnTo;
                //        }
                //    }

                //}
                if (_typekey == false && dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
                {
                    //string filter = "QstItemID ='" + dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value + "'";
                    //DataTable dt = new DataTable();
                    //_dtQSI.DefaultView.Table.Select(filter);
                    //if (_dtQSI.Rows.Count == 1)
                    //{

                    double AnFrom = Convert.ToDouble(dgv.Rows[e.RowIndex].Cells["colAnwerFrom"].Value);
                    double AnTo = Convert.ToDouble(dgv.Rows[e.RowIndex].Cells["colAnwerTo"].Value);
                    if (AnFrom != 0.0 || AnTo != 0.0)
                    {
                        if (AnFrom > Convert.ToDouble(dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()) ||
                                Convert.ToDouble(dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()) > AnTo)
                        {
                            dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = AnTo;
                        }
                    }
                    //}

                }
            }
        }

        private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (_Checkradio)
            {
                if (e.RowIndex >= 0 && e.ColumnIndex >=0)
                {
                    if (dgv.Columns[e.ColumnIndex].Name == "colCheck")
                    {                        
                        RadioButton Rd;
                        DataGridViewCellPanel DP = (DataGridViewCellPanel)this.dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Panel;
                        //if (DP.Colspan == 0)
                        //{
                        //    Rd = new RadioButton();                            
                        //    Rd.Dock = DockStyle.Fill;
                        //    Rd.Padding = new Gizmox.WebGUI.Forms.Padding(43, 0, 0, 0);
                        //    DP.Dock = DockStyle.Fill;
                        //    DP.Controls.Clear();
                        //    DP.Controls.Add(Rd);
                        //    DP.Colspan = 1;
                        //    DP.Rowspan = 1;

                        //    // Store reference to Cell
                        //    Rd.Tag = this.dgv.Rows[e.RowIndex].Cells[e.ColumnIndex];

                        //    // Update changed value to Cell
                        //    Rd.CheckedChanged += this.CellRadioButton_CheckedChanged;
                        //}
                        Rd = (RadioButton)DP.Controls[0];
                        
                        if (this.dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "0")
                            Rd.Checked = false;
                        else
                            Rd.Checked = true;
                    }
                }
            }
        }

        private void CellRadioButton_CheckedChanged(object sender, System.EventArgs e)
        {
            RadioButton DTP = (RadioButton)sender;
            if (DTP.Checked)
            {
                if (DTP != null && DTP.Tag != null)
                {

                    for (int i = 0; i < dgv.Rows.Count; i++)
                    {                        
                        this.dgv.Rows[i].Cells[((DataGridViewCell)DTP.Tag).ColumnIndex].Value = false;
                    }
                    ((DataGridViewCell)DTP.Tag).Value = DTP.Checked;
                   
                }
            }
        }

        private void dgv_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (dgv.Columns[e.ColumnIndex].Name == "colLookup")
            {
                
            }
            if (dgv.Columns[e.ColumnIndex].Name == "colCheck")
            {
                //if (_typekey == false && dgv.Rows[e.RowIndex].Cells["colQstItemID"].Value != null)
                //{
                //    string filter = "QstItemID ='" + dgv.Rows[e.RowIndex].Cells["colQstItemID"].Value + "'";
                //    DataTable dt = new DataTable();
                //    dt = _dtQSI.Copy();
                //    DataRow[] result = dt.Select(filter);
                //    foreach (DataRow row in result)
                //    {
                //        double AnFrom = (double)row["AnswerFrom"];
                //        double AnTo = (double)row["AnswerTo"]; //dt.Rows[0].Field<int>("AnswerTo");
                //        if (AnFrom != AnTo)
                //        {
                //            if (AnFrom > Convert.ToDouble(dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()) ||
                //                    Convert.ToDouble(dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()) > AnTo)
                //            {

                //                MessageBox.Show(sErr);
                //                dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = AnTo;
                //            }
                //        }
                //    }

                //}

                // even relation
                if (_dtRelation.Rows.Count > 0)
                {
                    if (dgv_ValueChanged != null)
                    {                        
                            foreach (DataRow row in _dtRelation.Rows)
                            {
                                if (dgv.Rows[e.RowIndex].Cells["colQstItemID"].Value.ToString() == row["ItemA"].ToString())
                                {
                                    if (row["ClassA"].ToString() == dgv.Rows[e.RowIndex].Cells["colClassID"].Value.ToString())
                                    {
                                        bool isbool = true;
                                        //if (row["IsEnabled"].ToString() == "1")
                                        //{
                                        //    isbool = true;
                                        //}
                                        dgv_ValueChanged(this, new DataGridViewCellEventHandler(dgv.Rows[e.RowIndex].Cells["colQstItemID"].Value.ToString()
                                            , dgv.Rows[e.RowIndex].Cells["colClassID"].Value.ToString(), row["ItemB"].ToString(), row["ClassB"].ToString()
                                                    , (double)row["Value"], isbool));
                                        return;
                                    }
                                    else
                                    {
                                        bool isbool = false;
                                        dgv_ValueChanged(this, new DataGridViewCellEventHandler(dgv.Rows[e.RowIndex].Cells["colQstItemID"].Value.ToString()
                                            , dgv.Rows[e.RowIndex].Cells["colClassID"].Value.ToString(), row["ItemB"].ToString(), row["ClassB"].ToString()
                                                    , 0, isbool));
                                    }
                                }
                            }
                        
                    }
                }
            }

            
        }

        
    }
}